package com.hollycrm.hollysqm.analyzer.solr.filter;

import com.hollycrm.hollysqm.analyzer.solr.action.Act;
import lombok.extern.log4j.Log4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhaihw on 2016/5/4.
 * 分发处理由合力发起的请求
 */
@Log4j
public class HollyDispatchFilter implements Filter{
    private static Map<String,Act> clazzMap = new HashMap<>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Enumeration<String> enums = filterConfig.getInitParameterNames();
        while(enums.hasMoreElements()){ //缓存类参数
            String name = enums.nextElement();
            String clazzName = filterConfig.getInitParameter(name);
            try {
                Class<Act> clazz = (Class<Act>) Class.forName(clazzName);
                Act act = clazz.newInstance();
                clazzMap.put(name, act);
            }catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url = httpRequest.getServletPath();
        int idx= url.lastIndexOf("/");
        if(idx > 0) {
            String actName = url.substring(idx + 1);
            log.info("url [" + url + "],act[" + actName + "]");
            Act act = clazzMap.get(actName);
            if(act == null)
                chain.doFilter(request, response);
            else {
                String json = act.execute();
                response.setContentType("text/plain;charset=utf-8");
                response.getWriter().write(json);
                response.flushBuffer();
            }
        }else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
